package com.tensquare.user.Interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1. 得到请求头
        String header = request.getHeader("Authorization");
        //2. 判断是否存在，存在就看是否是以bearer开头
        if (StringUtils.isNotBlank(header) && header.startsWith("Bearer")){
            //2.1 得到token
            String token = header.substring(7);
            //2.2解析
            Claims claims = jwtUtil.parseJWT(token);
            //2.3 判断token是否存在，存在就放到request中
            request.setAttribute("claims",claims);
        }
        return true;
    }
}

